package com.nicolascarrascob.clientesoap;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewDebug.IntToString;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Nicolas
 *
 */
public class MainActivity extends ListActivity {
	
	/**
	 * 
	 */
	private TextView txtResultadoServicio;
	
	ArrayList<Pelicula> peliculas;
	
	/**
	 * 
	 */
	private String URL = Constantes.HOST + "/ServicioWebSoap/services/CarteleraCineORMWS";
	/**
	 * 
	 */
	private String NAMESPACE = "http://ws.serviciosoap.pds.nicolascarrascob.com";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
      
        setContentView(R.layout.activity_main);
        peliculas = new ArrayList<Pelicula>();
        txtResultadoServicio = (TextView) findViewById(R.id.txt_resultado_servicio);
    }
    
    
    
    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		peliculas = new ArrayList<Pelicula>();
		setListAdapter(new PeliculasAdapter(MainActivity.this, 0, peliculas));
	}



	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
    	Intent intent = new Intent(MainActivity.this, UpdatePeliculaActivity.class);
    	intent.putExtra("pelicula", peliculas.get(position));
    	startActivity(intent);
	}

	/**
     * @param v
     */
    public void obtenerCartelera(View v){
    	txtResultadoServicio.setText("");
    	Log.d("", URL);
    	new ObtenerCarteleraBackground().execute();
    }
    
    /**
     * @param v
     */
    public void obtenerEstrenos(View v){
    	txtResultadoServicio.setText("");
    	new ObtenerEstrenosBackground().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_pelicula:
            	Intent intent = new Intent(MainActivity.this, AddPeliculaActivity.class);
            	startActivity(intent);
            	return true;
            default:
                return true;
        }
    }

	/**
     * @author Nicolas
     *
     */
    class ObtenerCarteleraBackground extends AsyncTask<Void, Void, String>{
    	
    	private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				MainActivity.this,
    				"Cartelera de Cine", 
    				"Espere mientras se carga la cartelera...", 
    				true);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {

			String resultadoJSON="";
			Log.d("", "1");
	    	String METHOD_NAME = "getCartelera";
	    	String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes =true;
			soapEnvelope.setOutputSoapObject(request);

			HttpTransportSE aht = new HttpTransportSE(URL);
			Log.d("Cliente SOAP", "Iniciando Consulta");
			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				Log.d("Cliente SOAP soapenvelope", soapEnvelope.toString());
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultadoJSON = resultString.toString();
				Log.d("Cliente SOAP", "Finalizando Consulta");
				
				
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
	    
			return resultadoJSON;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			if("".equals(result)){
				Toast.makeText(MainActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}else{
				try {
					peliculas = new ArrayList<Pelicula>();
					String texto = "";
					Log.d("", result);
					JSONObject resultado = new JSONObject(result);
					texto += resultado.getString("Titulo") +"\n";
					String contenido = resultado.getString("Contenido");
					Log.d("ClienteSoap", contenido);
					JSONArray peliculasJSONArray = new JSONArray(contenido);
					int cantPeliculas = peliculasJSONArray.length();
					for(int i = 0; i< cantPeliculas; i ++){
						Pelicula pelicula = new Pelicula();
						texto += peliculasJSONArray.getJSONObject(i).getString("Id") +"\n";
						pelicula.setId(peliculasJSONArray.getJSONObject(i).getString("Id"));
						texto += peliculasJSONArray.getJSONObject(i).getString("Titulo") +"\n";
						pelicula.setTitulo(peliculasJSONArray.getJSONObject(i).getString("Titulo"));
						texto += peliculasJSONArray.getJSONObject(i).getString("Clasificacion") +"\n";
						pelicula.setClasificacion(peliculasJSONArray.getJSONObject(i).getString("Clasificacion"));
						texto += peliculasJSONArray.getJSONObject(i).getString("Estreno") +"\n";
						pelicula.setEstreno(peliculasJSONArray.getJSONObject(i).getString("Estreno"));
						texto += peliculasJSONArray.getJSONObject(i).getString("Descripcion") +"\n";
						pelicula.setDescripcion(peliculasJSONArray.getJSONObject(i).getString("Descripcion"));
						texto += peliculasJSONArray.getJSONObject(i).getString("Genero") +"\n";
						pelicula.setGenero(peliculasJSONArray.getJSONObject(i).getString("Genero"));
						texto += "\n";
						peliculas.add(pelicula);
					}
					setListAdapter(new PeliculasAdapter(MainActivity.this, 0, peliculas));
//					txtResultadoServicio.setText(texto);
				} catch (JSONException e) {
					Toast.makeText(MainActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
				}
			}
		}
    }
    /**
     * @author Nicolas
     *
     */
    class ObtenerEstrenosBackground extends AsyncTask<Void, Void, String>{
    	
    	private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				MainActivity.this,
    				"Cartelera de Cine", 
    				"Espere mientras se carga la cartelera de estrenos...", 
    				true);
			super.onPreExecute();
		}
    	
    	@Override
    	protected String doInBackground(Void... params) {
    		
    		String resultadoJSON="";
    		String METHOD_NAME = "getEstrenos";
    		String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
    		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    		SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    		soapEnvelope.dotNet = true;
    		soapEnvelope.implicitTypes =true;
    		soapEnvelope.setOutputSoapObject(request);
    		
    		HttpTransportSE aht = new HttpTransportSE(URL);
    		
    		try {
    			aht.call(SOAP_ACTION, soapEnvelope);
    			SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
    			resultadoJSON = resultString.toString();
    			
    			
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (XmlPullParserException e) {
    			e.printStackTrace();
    		}
    		
    		return resultadoJSON;
    	}
    	
    	@Override
    	protected void onPostExecute(String result) {
    		super.onPostExecute(result);
    		progressDialog.dismiss();
    		if("".equals(result)){
				Toast.makeText(MainActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}else{
				txtResultadoServicio.setText(result);
			}
    		
    	}
    }
}
